﻿/* ***** BEGIN LICENSE BLOCK *****
 *   Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 * 
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Меню форума Vingrad.
 *
 * The Initial Developer of the Original Code is
 * Jefim Borissov.
 * Portions created by the Initial Developer are Copyright (C) 2006
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor (s):
 * Abramov Daniel
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 * 
 * ***** END LICENSE BLOCK ***** */

function topic (id, name) {
    this.id = id;
    this.name = name;
}


var favTopicsManager = {
    topics: new Array (),
    topicsCount: 0,
    topicsMenu: null,
    topicsPopupMenu: null,
    topicsXml: null,

    init: function () {
        this.topicsXml = xmlhelper.load (settings.getFavTopicListUrl ());
        this.topicsMenu = $ ("vingradmenu-tb-favtopics"); // меню избранное
    	this.topicsPopupMenu = $ ("vingradmenu-tb-favtopics-container"); // контейнер для менюитемов
        this.parseTopics (); // парсим (из favtopics.xml)
    	this.populateTopicsList (); // выводим их
        this.locationChanged ();
        locationWatcher.init (this.locationChanged);
    },     
    // дохнем   
    deinit: function () {
        this.serializeTopics (this.formXmlTree ()); // сериализуем топики в файл
        locationWatcher.deinit ();
    }, 
    increaseForumsCount: function () {
        this.topicsCount ++;
        this.onTopicsCountChanged ();
    },
    decreaseForumsCount: function () {
        this.topicsCount --;
        this.onTopicsCountChanged ();
    },
    // парсим список избранных топиков из настроек
    populateTopicsList: function () {    
        var xsl = xmlhelper.load (settings.getFavTopicListXslUrl ());
        var topics = xmlhelper.transform (this.topicsXml, xsl);
        this.topicsPopupMenu.appendChild (topics);
        this.onTopicsCountChanged ();           
    },  
    // парсим список избранных топиков из favtopics.xml в topics
    parseTopics: function () {     
        var xmlTopics = this.topicsXml.getElementsByTagName("topic");
        for (i = 0; i < xmlTopics.length; i++) {
            var xmlTopic = xmlTopics[i];
            this.topics[xmlTopic.getAttribute("id")] = new topic (xmlTopic.getAttribute("id"), xmlTopic.getAttribute("name"));
        }
        this.topicsCount = xmlTopics.length;
    },  
    // загоняем forums в дерево
    formXmlTree: function () {
        var xml = document.implementation.createDocument("", "", null);
        var root = xml.createElement("favtopics");
        for (i in this.topics) {
            topic = this.topics[i];
            if (topic != null) {
                var xmlTopic = xml.createElement("topic");
                xmlTopic.setAttribute("id", topic.id);
                xmlTopic.setAttribute("name", topic.name);
                root.appendChild (xmlTopic);
            }
        }
        xml.appendChild (root);
        return xml;        
    },
    // сохраняем дерево в файл
    serializeTopics: function (xml) {
        var file = utils.getExtFolder ();
        file.append ("chrome");
        file.append("content");
        file.append("favtopics.xml");
        xmlhelper.save (xml, file);
    },
    // нажата кнопочка-звёздочка
    toggle: function () {
        var topicId = utils.tryParseTopicId();
        if (topicId != null) {
            if (this.isFavTopic (topicId)) {
                if (utils.yesNoPrompt ("Удаление из избранного...", 'Удалить "' + this.topics[topicId].name + '" из избранного?')) {
                    this.removeFavTopic (topicId);
                }
            } else {
                var title = utils.refiningPrompt("Добавить в избранное...", "Введите заголовок темы:", utils.tryParseTopicTitle ());
                if (title != null) {
                    this.addFavTopic (topicId, title);
                }
            }
        }
    },
    addFavTopic: function (topicId, title) {
        this.topics[topicId] = new topic (topicId, title);
        var xulTopic = document.createElement ("menuitem");
        xulTopic.setAttribute("id", "vingradmenu-tb-favtopics-topic-" + topicId);
        xulTopic.setAttribute("label", title);
        xulTopic.setAttribute("tooltiptext", title);
        xulTopic.setAttribute("oncommand", "navigator.toTopic(" + topicId + "); event.stopPropagation();");
        xulTopic.setAttribute("class", "menuitem-iconic");
        this.increaseForumsCount ();
        this.topicsPopupMenu.insertBefore (xulTopic, $ ("vingradmenu-tb-favtopics-cleanup-sep"));
        this.locationChanged ();
    },
    removeFavTopic: function (topicId) {
        this.topics[topicId] = null;
        this.topicsPopupMenu.removeChild ($ ("vingradmenu-tb-favtopics-topic-" + topicId));
        this.decreaseForumsCount ();
        this.locationChanged ();
    },
    isFavTopic: function (id) {
        return (this.topics[id] != null);
    },
    cleanup: function () {
        if (utils.yesNoPrompt ("Очистить список избранных тем", "Вы уверены, что хотите полностью очистить список избранных тем?")) {
            for (topicId in this.topics) {
                if (topic != null) {
                    this.topics[topicId] = null;
                    this.topicsPopupMenu.removeChild ($ ("vingradmenu-tb-favtopics-topic-" + topicId));
                    this.decreaseForumsCount ();
                }
            }                
        }
        this.locationChanged ();
    },
    locationChanged: function () {
        var topicId = utils.tryParseTopicId();
        if (topicId != null) {
            if (favTopicsManager.topics[topicId] != null) { // уже в избранном
                    favTopicsManager.topicsMenu.setAttribute("toggled", "true");
                    favTopicsManager.topicsMenu.setAttribute("tooltiptext", 'Удалить"' + favTopicsManager.topics[topicId].name + '" из избранного...');
            } else { // ещё не в избранном
                    favTopicsManager.topicsMenu.setAttribute("toggled", "false");
                    favTopicsManager.topicsMenu.setAttribute("tooltiptext", 'Добавить"' + utils.tryParseTopicTitle () + '" в избранное...');
            }
        } else { // это не винградовская тема
            favTopicsManager.topicsMenu.setAttribute("toggled", "false");
            favTopicsManager.topicsMenu.setAttribute("tooltiptext", "В избранное можно добавить только темы форума!");
        } 
    },
    onTopicsCountChanged: function () {
        if (this.topicsCount > 0) {
           $ ("vingradmenu-tb-favtopics-empty").setAttribute("hidden", "true");     
           $ ("vingradmenu-tb-favtopics-cleanup-sep").setAttribute("hidden", "false");  
           $ ("vingradmenu-tb-favtopics-cleanup").setAttribute("hidden", "false");
        } else if (this.topicsCount == 0) { 
           $ ("vingradmenu-tb-favtopics-empty").setAttribute("hidden", "false");    
           $ ("vingradmenu-tb-favtopics-cleanup-sep").setAttribute("hidden", "true");  
           $ ("vingradmenu-tb-favtopics-cleanup").setAttribute("hidden", "true");
        }
    },
    suggestAddFavTopic: function (id, title) {
        if (!this.isFavTopic (id)) {
            var choice = settings.addFavTopicDefaultBehavior  ();
            if (choice == "ask") {
                    var add = utils.yesNoPrompt ("Добавить в избранное?", 'Вы посетили тему "' + title + '" более пяти раз. Возможно, вы желаете добавить её в избранное?' );
                    if (add) {
                        this.addFavTopic (id, title);
                    } else {
                        settings.setIgnoreTopicVisits (id);
                    }
            } else if (choice == "add") {
                    this.addFavTopic (id, title);
            }
        }
    }
}
